import {
  Avatar,
  Card,
  Collapse,
  Flex,
  Tabs,
  Tooltip,
  Typography,
  Button,
  Modal,
  Input,
  message,
  Popconfirm,
  Empty,
} from "antd";
import {
  UserOutlined,
  VideoCameraAddOutlined,
  HddOutlined,
  StarOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

import { useEffect, useRef, useState } from "react";
import to from "await-to-js";
import { useSelector } from "react-redux";
import { SettingOutlined } from "@ant-design/icons";
import {
  getUserVideo as getUserVideoApi,
  getWatchHistory as getWatchHistoryApi,
  addCollect as addCollectApi,
  getCollectList as getCollectListApi,
  getCollections as getCollectionsApi,
  deleteCollect as deleteCollectApi,
} from "@/api/personal/index";
const { Paragraph, Text } = Typography;

const Index: React.FC = () => {
  useEffect(() => {});
  // 获取全局用户数据状态
  const { userInfo } = useSelector((state) => state.user);
  console.log(userInfo);
  
  // 获取用户上传视频参数
  const getUserVideoParams = useRef({
    uploaderId: "",
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    orderByColumn: "createTime",
  });
  // 获取用户历史记录参数
  const getUserWatchHistory = useRef({
    userId: "",
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    orderByColumn: "createTime",
  });
  // 用户视频列表
  const [myVideoList, setMyVideoList] = useState([]);
  useEffect(() => {
    getUserCollectsParams.current.userId = userInfo.userId;
    getUserVideo();
    getWatchHistory();
    getCollectList();
  }, []);
  //  获取用户上传视频列表
  const getUserVideo = async () => {
    const [err, res] = await to(getUserVideoApi(getUserVideoParams.current));
    if (!err) {
      console.log(res);
      setMyVideoList(res.rows);
    }
  };
  const [watchHistoryList, setWatchHistoryList] = useState([]);
  // 获取用户观看历史
  const getWatchHistory = async () => {
    getUserWatchHistory.current.userId = userInfo.userId;
    const [err, res] = await to(
      getWatchHistoryApi(getUserWatchHistory.current)
    );
    if (!err) {
      console.log(res);
      res.rows.forEach((item: any) => {
        item.title = item.videoVo.title;
        item.images = item.videoVo.images;
      });
      setWatchHistoryList(res.rows);
    }
  };
  // 收藏夹的操作模块
  const genExtra = (id: number | string) => (
    <>
      <SettingOutlined
        className="mr-20px"
        onClick={(event) => {
          // If you don't want click extra trigger collapse, you can prevent this:
          console.log(id);
          event.stopPropagation();
        }}
      />
      <Popconfirm
        title="Delete the task"
        description="Are you sure to delete this task?"
        onConfirm={() => handleDelete(id as string)}
        onCancel={cancel}
        okText="Yes"
        cancelText="No"
      >
        <DeleteOutlined
          onClick={(event) => {
            // If you don't want click extra trigger collapse, you can prevent this:
            console.log(id);

            event.stopPropagation();
          }}
        />
      </Popconfirm>
    </>
  );
  // 确定删除收藏夹按钮
  const handleDelete = async (id: string) => {
    const [err, res] = await to(deleteCollectApi(id));
    if (!err) {
      console.log(res);
      message.success("删除成功");
      await getCollectList();
    } else {
      message.error("删除失败");
    }
  };
  // 取消删除按钮
  const cancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    message.info("取消成功");
  };
  // 获取收藏夹列表参数
  const getUserCollectParams = useRef({
    userId: "",
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    orderByColumn: "createTime",
  });
  // 收藏夹列表
  const [collectionList, setCollectionList] = useState([]);
  // 获取收藏列表
  const getCollectList = async () => {
    getUserCollectParams.current.userId = userInfo.userId;
    const [err, res] = await to(
      getCollectListApi(getUserCollectParams.current)
    );
    if (!err) {
      setCollectionList((collectionList: any) => {
        collectionList = res.rows;
        collectionList.forEach((item) => {
          item.label = item.name;
          item.key = item.collectFolderId;
          item.extra = genExtra(item.collectFolderId);
        });
        return collectionList;
      });
    }
  };
  // 获取收藏夹下的收藏列表
  const getUserCollectsParams = useRef({
    userId: "",
    collectFolderId: "",
    pageSize: 10,
    pageNum: 1,
    orderByColumn: "createTime",
  });
  // 收藏视频列表
  const [collectVideoList, setCollectionVideoList] = useState([]);
  // 是否切换收藏夹
  // 当前文件夹id
  const currentCollectionId = useRef("");

  const navigateTo = useNavigate();

  // 视频播放按钮
  const handlePlay = (videoInfo: any) => {
    console.log(videoInfo);
    // 跳转页面并传递参数
    navigateTo("/home/playPage", { state: { videoInfo } });
  };
  // 获取收藏列表
  const getCollections = async () => {
    const [err, res] = await to(
      getCollectionsApi(getUserCollectsParams.current)
    );
    if (!err) {
      // 设置文件夹的视频列表
      setCollectionVideoList((collectVideoList) => {
        collectVideoList = res.rows;
        console.log(collectVideoList);
        // 设置指定文件夹的children
        setCollectionList((collectionList) => {
          collectionList.forEach((item: any) => {
            // 找到当前点击的文件夹并赋予children
            if (item.collectFolderId === currentCollectionId.current) {
              if (!res.rows || res.rows.length === 0) {
                // 如果视频列表为空
                item.children = <Empty description={<span>暂无数据</span>} />;
              } else {
                item.children = (
                  <Flex key={item.collectFolderId} wrap="wrap">
                    {collectVideoList.map((subItem: any) => {
                      return (
                        <>
                          <div
                            key={subItem.videoVo.videoId}
                            onClick={() => handlePlay(subItem.videoVo)}
                            className="cursor-pointer"
                          >
                            <div
                              className="ml-20px w235px h145px mb-5px"
                              style={{
                                borderRadius: "2%",
                                border: "1px solid #999",
                              }}
                            >
                              {/* {(item.images ?? "" !== "") && ( */}
                              <img
                                src={subItem.videoVo.images ?? ""}
                                // src="https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"
                                alt=""
                                className="absolute w-233px h-144px object-contain"
                                style={{ borderRadius: "3%" }}
                              />
                              {/* )} */}
                              <Tooltip title="开始播放">
                                <img
                                  style={{
                                    width: "40px",
                                    height: "40px",
                                    marginLeft: "100px",
                                    marginTop: "54px",
                                  }}
                                  className="absolute  cursor-pointer"
                                  src={"bigplay.png"}
                                  alt=""
                                />
                              </Tooltip>
                            </div>
                            <Paragraph
                              ellipsis={{ rows: 1, expandable: false }}
                              className="ml-20px w240px h-20px"
                              style={{
                                lineHeight: "20px",
                                fontWeight: "600",
                                color: "#444",
                              }}
                            >
                              {subItem.videoVo.title}
                            </Paragraph>
                            <div
                              className="ml-20px mt--10px mb-10px"
                              style={{ color: "#666", fontSize: "14px" }}
                            >
                              <span>
                                <UserOutlined />
                                {subItem.videoVo.createBy}
                              </span>
                              <span className="ml-20px">
                                {subItem.createTime}
                              </span>
                            </div>
                          </div>
                        </>
                      );
                    })}
                  </Flex>
                );
              }
            }
          });
          return collectionList;
        });
        return collectVideoList;
      });
      console.log(currentCollectionVideoList.current);
    }
  };
  // 点击切换收藏夹
  const handleChangeCollect = async (key: string | string[]) => {
    if (
      currentCollectionId.current === "" ||
      currentCollectionId.current != key[0]
    ) {
      currentCollectionId.current = key[0];
      getUserCollectsParams.current.collectFolderId = key[0];
      getCollections();
    }
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("");
  const collectParams = useRef({
    userId: "",
    name: "",
  });
  // 新增收藏夹
  const handleAddCollection = () => {
    setIsModalOpen(true);
    setModalTitle("新增收藏夹");
  };
  // 确定新增收藏夹
  const handleOk = async () => {
    collectParams.current.userId = userInfo.userId;
    const [err] = await to(addCollectApi(collectParams.current));
    if (!err) {
      message.success("添加成功");
      await getCollectList();
      setIsModalOpen(false);
    } else {
      message.error("添加失败");
    }
  };

  // 新增收藏夹取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // tab页面
  const tabs = [
    {
      icon: VideoCameraAddOutlined,
      title: "我的视频",
      children: (
        <>
          {myVideoList.length > 0 && (
            <Flex className="flex-wrap">
              {myVideoList.map((item) => {
                return (
                  <div
                    key={item.videoId}
                    onClick={() => handlePlay(item)}
                    className="cursor-pointer"
                  >
                    <div
                      className="ml-20px w235px h145px mb-5px"
                      style={{ borderRadius: "2%", border: "1px solid #999" }}
                    >
                      {/* {(item.images ?? "" !== "") && ( */}
                      <img
                        src={item.images ?? ""}
                        // src="https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"
                        alt=""
                        className="absolute w-233px h-144px object-contain"
                        style={{ borderRadius: "3%" }}
                      />
                      {/* )} */}
                      <Tooltip title="开始播放">
                        <img
                          style={{
                            width: "40px",
                            height: "40px",
                            marginLeft: "100px",
                            marginTop: "54px",
                          }}
                          className="absolute  cursor-pointer"
                          src={"bigplay.png"}
                          alt=""
                        />
                      </Tooltip>
                    </div>
                    <Paragraph
                      ellipsis={{ rows: 1, expandable: false }}
                      className="ml-20px w240px h-20px"
                      style={{
                        lineHeight: "20px",
                        fontWeight: "600",
                        color: "#444",
                      }}
                    >
                      {item.title}
                    </Paragraph>
                    <div
                      className="ml-20px mt--10px mb-10px"
                      style={{ color: "#666", fontSize: "14px" }}
                    >
                      <span>
                        <UserOutlined />
                        {item.createBy}
                      </span>
                      <span className="ml-20px">{item.createTime}</span>
                    </div>
                  </div>
                );
              })}
            </Flex>
          )}
          {!myVideoList && <Empty description={<span>暂无数据</span>} />}
        </>
      ),
    },
    {
      icon: HddOutlined,
      title: "最近观看",
      children: (
        <>
          <>
            {watchHistoryList && (
              <Flex className="flex-wrap">
                {watchHistoryList.map((item) => {
                  return (
                    <div
                      key={item.videoId}
                      onClick={() => handlePlay(item)}
                      className="cursor-pointer"
                    >
                      <div
                        className="ml-20px w235px h145px mb-5px"
                        style={{ borderRadius: "2%", border: "1px solid #999" }}
                      >
                        {/* {(item.images ?? "" !== "") && ( */}
                        <img
                          src={item.images ?? ""}
                          // src="https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"
                          alt=""
                          className="absolute w-233px h-144px object-contain"
                          style={{ borderRadius: "3%" }}
                        />
                        {/* )} */}
                        <Tooltip title="开始播放">
                          <img
                            style={{
                              width: "40px",
                              height: "40px",
                              marginLeft: "100px",
                              marginTop: "54px",
                            }}
                            className="absolute  cursor-pointer"
                            src={"bigplay.png"}
                            alt=""
                          />
                        </Tooltip>
                      </div>
                      <Paragraph
                        ellipsis={{ rows: 1, expandable: false }}
                        className="ml-20px w240px h-20px"
                        style={{
                          lineHeight: "20px",
                          fontWeight: "600",
                          color: "#444",
                        }}
                      >
                        {item.title}
                      </Paragraph>
                      <div
                        className="ml-20px mt--10px mb-10px"
                        style={{ color: "#666", fontSize: "14px" }}
                      >
                        <span>
                          <UserOutlined />
                          {item.createBy}
                        </span>
                        <span className="ml-20px">{item.createTime}</span>
                      </div>
                    </div>
                  );
                })}
              </Flex>
            )}

            {!watchHistoryList && <Empty description={<span>暂无数据</span>} />}
          </>
        </>
      ),
    },
    {
      icon: StarOutlined,
      title: "我的收藏",
      children: (
        <>
          <Button
            type="primary"
            onClick={handleAddCollection}
            className="mb-20px"
          >
            新增收藏夹
          </Button>
          <Collapse
            accordion
            onChange={handleChangeCollect}
            // expandIconPosition={expandIconPosition}
            items={collectionList}
          />
        </>
      ),
    },
  ];

  return (
    <>
      <div>
        {/* top */}
        <Card style={{ width: "92vw" }}>
          <img
            style={{ width: "100%", height: "100%" }}
            src={"bg.png"}
            alt=""
          />
          <div style={{ marginTop: "-110px", marginLeft: "30px" }}>
            <Flex>
              <Avatar size={64} icon={<UserOutlined />} />
              <div>
                <div
                  style={{
                    fontSize: "16px",
                    fontWeight: "500",
                    color: "white",
                    margin: "5px 0 0 20px",
                  }}
                >
                  {userInfo.createBy}
                </div>

                <div
                  style={{
                    fontSize: "13px",
                    fontWeight: "400",
                    color: "white",
                    margin: "10px 0 0 20px",
                  }}
                >
                  这是个性签名
                </div>
              </div>
            </Flex>
          </div>
          {/* tabs */}
          <div style={{ marginTop: "60px" }}>
            <Tabs
              defaultActiveKey="1"
              type="card"
              items={tabs.map((item, i) => {
                return {
                  label: (
                    <span>
                      <item.icon />
                      {item.title}
                    </span>
                  ),
                  key: i,
                  children: item.children,
                };
              })}
            />
          </div>
          <Modal
            title={modalTitle}
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Input
              onChange={(e) => (collectParams.current.name = e.target.value)}
              placeholder="请输入收藏夹名称"
            />
          </Modal>
        </Card>
      </div>
    </>
  );
};

export default Index;
